package com.ruoyi.web.controller.product;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.shop.common.utils.BeanConvertUtils;
import com.ruoyi.shop.modules.domain.Product;
import com.ruoyi.shop.modules.domain.vo.ProductVo;
import com.ruoyi.shop.modules.service.IOrderService;
import com.ruoyi.shop.modules.service.IProductService;
import com.ruoyi.shop.nosql.es.domain.EsProduct;
import com.ruoyi.shop.nosql.es.service.EsProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;

/**
 * 商品信息Controller
 *
 * @author zjc
 * @date 2024-06-22
 */
@RestController
@RequestMapping("/product/product")
public class ProductController extends BaseController {
    @Autowired
    private IProductService productService;
    @Autowired
    private IOrderService orderService;
    @Autowired
    private EsProductService esProductService;

    /**
     * 查询商品信息列表
     */
    @PreAuthorize("@ss.hasPermi('product:product:list')")
    @GetMapping("/list")
    public TableDataInfo list(Product product) {
        startPage();
        List<ProductVo> list = productService.selectProductList(product);
        return getDataTable(list);
    }

    /**
     * 导出商品信息列表
     *
     */
    @PreAuthorize("@ss.hasPermi('product:product:export')")
    @Log(title = "商品信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Product product) {
        List<ProductVo> list = productService.selectProductList(product);
        ExcelUtil<Product> util = new ExcelUtil<Product>(Product.class);
//        util.exportExcel(response, list, "商品信息数据");
    }

    /**
     * 获取商品信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('product:product:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(productService.selectProductById(id));
    }

    /**
     * 新增商品信息
     */
    @PreAuthorize("@ss.hasPermi('product:product:add')")
    @Log(title = "商品信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Product product) {
        return toAjax(productService.insertProduct(product));
    }

    /**
     * 修改商品信息
     */
    @PreAuthorize("@ss.hasPermi('product:product:edit')")
    @Log(title = "商品信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Product product) {
        return toAjax(productService.updateProduct(product));
    }

    /**
     * 删除商品信息
     */
    @PreAuthorize("@ss.hasPermi('product:product:remove')")
    @Log(title = "商品信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(productService.deleteProductByIds(ids));
    }

    //前台查询商品接口
    @GetMapping("/query")
    public AjaxResult query(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                               @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        List<ProductVo> list = productService.selectProductVoList(pageNum, pageSize);
        return success(list);
    }

    @GetMapping("/like")
    public CompletableFuture<TableDataInfo> guessLike() {
        // 开始分页
        startPage();
        // 获取用户ID
        Long userId = getUserId();

        // 1. 基于用户推荐
        CompletableFuture<List<ProductVo>> userBasedRecommendationFuture = CompletableFuture.supplyAsync(() -> {
            List<Product> guessLikeProducts = orderService.getGuessLikeProducts(userId);
            return BeanConvertUtils.convertProductsToVos(guessLikeProducts, Product::getAlbumPics);
        });

        // 2. 基于商品推荐
        CompletableFuture<List<ProductVo>> productBasedRecommendationFuture = CompletableFuture.supplyAsync(() -> {
            List<Long> pids = productService.selectProductOperHistoryByUid(userId);
            if (!pids.isEmpty()) {
                Page<EsProduct> recommended = esProductService.recommend(pids.get(0), 1, 8);
                List<EsProduct> esProducts = recommended.getContent();
                return BeanConvertUtils.convertProductsToVos(esProducts, EsProduct::getAlbumPics);
            }
            return Collections.emptyList();
        });

        // 3. 数据库随机抽8个商品Vo
        CompletableFuture<List<ProductVo>> randProductsFuture = CompletableFuture.supplyAsync(() -> productService.selectProductVoRand(8));

        // 合并结果
        return CompletableFuture.allOf(userBasedRecommendationFuture, productBasedRecommendationFuture, randProductsFuture).thenApply(v -> {
            try {
                List<ProductVo> usrProducts = new ArrayList<>();
                usrProducts.addAll(userBasedRecommendationFuture.get());
                usrProducts.addAll(productBasedRecommendationFuture.get());
                usrProducts.addAll(randProductsFuture.get());
                // 4. 合并商品Vo列表，并随机抽取8个商品
                List<ProductVo> finalVos = usrProducts.stream().distinct().limit(8).collect(Collectors.toList());
                // 返回商品Vo列表的表格数据
                return getDataTable(finalVos);
            } catch (InterruptedException | ExecutionException e) {
                throw new RuntimeException(e);
            }
        });
    }


}
